import { useUserStore } from '@/store/modules/user'
import storage from './storage'

export const auth = {
  // 检查登录状态
  isLoggedIn() {
    const token = storage.getToken()
    return !!token
  },
  
  // 获取用户信息
  async getUserInfo() {
    const userStore = useUserStore()
    if (!this.isLoggedIn()) {
      return null
    }
    
    if (userStore.userInfo) {
      return userStore.userInfo
    }
    
    try {
      const result = await userStore.getUserProfile()
      return result.success ? result.data : null
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  },
  
  // 登录
  async login(phone, password) {
    const userStore = useUserStore()
    try {
      const result = await userStore.login(phone, password)
      if (result.success) {
        storage.setToken(userStore.token)
        storage.setUserInfo(userStore.userInfo)
      }
      return result
    } catch (error) {
      return { success: false, message: error.message }
    }
  },
  
  // 登出
  logout() {
    const userStore = useUserStore()
    userStore.logout()
    storage.clear()
    
    // 跳转到登录页
    uni.reLaunch({
      url: '/pages/index/index'
    })
  },
  
  // 检查权限
  checkPermission(permission) {
    const userStore = useUserStore()
    if (!userStore.userInfo) return false
    
    // 这里可以根据用户角色判断权限
    const permissions = userStore.userInfo.permissions || []
    return permissions.includes(permission)
  },
  
  // 需要登录的页面守卫
  requireAuth() {
    if (!this.isLoggedIn()) {
      uni.navigateTo({
        url: '/pages/index/index'
      })
      return false
    }
    return true
  }
}

export default auth